import React, { useState } from 'react'
import { View, Picker } from '@tarojs/components'
import Taro,{ useDidShow, usePullDownRefresh, useReachBottom } from '@tarojs/taro'
import { AtList, AtListItem } from 'taro-ui'
import { request, formatDate } from '@/utils'
import './index.less'



// const SELECTOR = [{text: '全部', value: 0}, {text: '加油成功', value: 1}, {text: '加油失败', value:2}]

const  FightingDetails = () => {
  const [pageIndex, setPageIndex] = useState(1)
  const [total, setTotal] = useState(0)
  const [list, setList] = useState([])
  const [dateSel, setDateSel] = useState('开始时间')
  const [dateMonth, setDateMonth] = useState('')
  const [dateMonthEnd, setDateMonthEnd] = useState('')
  const [dateSelEnd, setDateSelEnd] = useState('结束时间')
  const [cardList, setCardList] = useState([])
  const [extraText, setExtraText] = useState('请选择车队')
  const [role, setRole] = useState('')
  const [carId, setCarId] = useState('')
  const [totalOil, setTotalOil] = useState(0)
  const [oliName, setOliName] = useState('请选择油站')
  const [oliId, setOliId] = useState('')
  const [oliList, setOliList] = useState([])
  const [show, setShow] = useState(false)
  const [type, setType] = useState()
  const [maxTime, setMaxTime] = useState(null)
  const [minTime, setMinTime] = useState(null)
  const getList = async (day, id, oId, index,  flag, dayEnd) => {
    Taro.showLoading({mask: true})
    const data = await request({url: 'hkshihua/operator/getOperatorOrderDetail', data: {supplierId: oId !== '' && !oId ? oliId : oId ,motorcadeId: id !== '' && !id ? carId : id, dateMonth: day !== '' && !day ? dateMonth : day, dateMonthEnd: dayEnd !== '' && !dayEnd ? dateMonthEnd : dayEnd, pageIndex: index || pageIndex}})
    const newData = flag ? [...list, ...data.list] : data.list
    setList(newData)
    setTotal(data.total)
    setTotalOil(data.totalOil)
  }
  const getOliList = async () => {
    Taro.showLoading({mask: true})
    const data = await request({url: 'hkshihua/user/supplier/list', data: { pageIndex: 1, pageSize: 10000}})
    setOliList([{name: '全部', id: ''},...data.list])
  }
  const getCardList = async () => {
    Taro.showLoading({mask: true})
    const data = await request({url: 'hkshihua/user/motorcade/getMotorcadeList', data: { pageIndex: 1, pageSize: 10000}})
    setCardList([{name: '全部', userId: ''},...data.list])
  }
  const onChange = (e) => {
    const { detail: { value }}= e
    const target = cardList[value]
    setExtraText(target.name)
    setCarId(target.userId)
    setPageIndex(1)
    getList(dateMonth, target.userId, oliId, 1, false,dateMonthEnd)
  }
  const onOliChange = (e) => {
    const { detail: { value }}= e
    const target = oliList[value]
    setOliName(target.name)
    setOliId(target.id)
    setPageIndex(1)
    getList(dateMonth, carId, target.id, 1, false,dateMonthEnd)
  }
  usePullDownRefresh(async () => {
    await resetParams()
    await getList('', '', '' ,1, '')
    Taro.stopPullDownRefresh()
  })
  useReachBottom(async () => {
    await setPageIndex(pageIndex + 1)
    if(total <= pageIndex * 10) return
    await getList(dateMonth, carId, oliId ,pageIndex + 1, true, dateMonthEnd)
  })
  const resetParams = async () => {
    await setPageIndex(1)
    setCarId('')
    setOliId('')
    setOliName('请选择油站')
    setExtraText('请选择车队')
    setDateMonth('')
    setDateMonthEnd('')
    setDateSelEnd('结束时间')
    setDateSel('开始时间')
  }
  useDidShow(async () => {
    const data = await  Taro.getStorage({key: 'userInfo'})
    const myRole = JSON.parse(data.data).user.role
    setRole(myRole)
    await resetParams()
    getList('', '', '' ,1, '')
    if(myRole === 'ADMINISTRATOR') {
      getCardList()
      getOliList()
    }
  })

  const handleClose = () => {
    setShow(false)
  }
  const handleConfirm = (e) => {
   const { detail } = e
   const time = formatDate('YYYY-MM-DD hh:mm', detail)
   if(type === 1) {
     setDateMonth(time)
     setDateSel(time)
     getList(time, carId, oliId, pageIndex, false, dateMonthEnd)
     setMaxTime(null)
     setMinTime(detail)
   } else {
    setDateMonthEnd(time)
    setDateSelEnd(time)
    setMaxTime(detail)
    setMinTime(undefined)
    getList(dateMonth, carId, oliId, pageIndex, false, time)
   }
    setShow(false)
  }
  const handleCancel = () => {
    setShow(false)
  }
  const handleDate = (t) => {
    setType(t)
    setShow(true)
  }
  return (
    <View >
        <View style={{position: role === 'ADMINISTRATOR' ? 'fixed' : 'static' ,width: '100%', top: 0, left: 0}}>
        {role === 'ADMINISTRATOR' &&
                <View className='my-picker'>
                  <Picker  mode='selector' rangeKey='name' range={cardList} onChange={onChange}>
                    <View>{extraText}</View>
                 </Picker>
                 <Picker  mode='selector' rangeKey='name' range={oliList} onChange={onOliChange}>
                 <View>{oliName}</View>
                </Picker>
                </View>
}
        <View>
        <AtList className='my-picker'>
          <View className='item' onClick={() => {handleDate(1)}}>
            {dateSel}
          </View>
          <View className='item' onClick={() => {handleDate(2)}}>
            {
              dateSelEnd
            }
          </View>
        </AtList>
        </View>
        <View>
        {
          role === 'ADMINISTRATOR' && <AtList>
            <AtListItem title='总油量' extraText={totalOil || 0} />
          </AtList>
        }
        </View>
        </View>
        <View className={role === 'ADMINISTRATOR' ? 'm-list-1 my-list' : 'm-list-1'}>
          {list.map((item) => {
            return <View key={item.id} className='m-item-1'>
            <View className='at-row'>
              <View className='at-col at-col-10 at-col--wrap'>
                <View className='at-row'>
                  <View className='at-col at-col-6 at-col--wrap'>{item.payerName}</View>
                  <View className='at-col at-col-8 at-col--wrap'>加油量 {item.num}升</View>
                </View>
                <View className='at-row'>
                  <View className='at-col at-col-6 at-col--wrap'>{item.name}</View>
                  <View className='at-col at-col-8 at-col--wrap'>{item.licensePlateNumber}</View>
                </View>
                <View className='at-row'>
                  <View className='at-col at-col-6 at-col--wrap'>加油工:{item.createUserName}</View>
                  <View className='at-col at-col-8 at-col--wrap'>{item.createTime}  </View>
                </View></View>
              {/* <View className='at-col at-col-2 at-col--wrap'>图片</View> */}
            </View>
          </View>
          })}
          {list.length <= 0 && <View className='no-data'>暂无数据</View>}
          {pageIndex * 10 >= total && list.length > 0 && <View className='no-data'>暂无更多数据</View>}
          <View style={{height: '40px'}}></View>
        </View>
        <van-popup
          show={show}
          position='bottom'
          custom-style='height: 20%;'
          onClose={handleClose}
        >
          {type === 1 && <vant-datetime-picker  onCancel={handleCancel} onConfirm={handleConfirm} value={dateMonth ? new Date(dateMonth.replace(/\-/g, '/')).getTime() : new Date().getTime()} maxDate={maxTime || new Date().getTime()}  type='datetime' />}
          {type === 2 && <vant-datetime-picker minDate={minTime} onCancel={handleCancel} onConfirm={handleConfirm} value={dateMonthEnd ? new Date(dateMonthEnd.replace(/\-/g, '/')).getTime() : new Date().getTime()} maxDate={maxTime || new Date().getTime()}  type='datetime' />}
        </van-popup>

      </View>
  )
}


export default FightingDetails
